import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/model/tag_archive_tags_model.dart';
import 'package:flutter_bilibili/core/model/video_model.dart';
import 'package:flutter_bilibili/core/service/request/video_play_request.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_bilibili/ui/shared/math_compute.dart';

import '../../../widgets/build_icon_info.dart';
import '../../../widgets/height_reporter.dart';

GlobalKey<_ExpandedWidgetState> cutDownWidgetKey = GlobalKey();

class buildVideoPlayVideoInfo extends StatefulWidget {
  HYVideoModel video;

  buildVideoPlayVideoInfo(this.video, {Key? key}) : super(key: key);

  @override
  State<buildVideoPlayVideoInfo> createState() =>
      _buildVideoPlayVideoInfoState();
}

class _buildVideoPlayVideoInfoState extends State<buildVideoPlayVideoInfo> {
  String _followers = "粉丝";
  int _videos = 0;
  bool isExpanded = false;
  List<HYTagArchiveTagsModel> tags = [];
  List<Widget> tagWidgets = [];

  @override
  void initState() {
    HYVideoRequestRequest.getRelationStatData(widget.video.owner.mid)
        .then((value) {
      _followers = value.data.followerText;
      setState(() {});
    });
    HYVideoRequestRequest.getSpaceNavNumData(widget.video.owner.mid)
        .then((value) {
      _videos = value.data.video;
      setState(() {});
    });
    HYVideoRequestRequest.getTagArchiveTagsData(widget.video.aid).then((value) {
      tags.clear();
      tags.addAll(value);
      for (HYTagArchiveTagsModel tag in tags) {
        tagWidgets.add(buildVideoTag(tag.tagName));
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 15.px, horizontal: 20.px),
      child: Column(
        children: [
          buildVideoPlayVideoInfoOwnerInfo(
              widget.video.owner.face, widget.video.owner.name),
          SizedBox(
            height: 15.px,
          ),
          buildVideoPlayVideoInfoVideoTitle(),
          SizedBox(
            height: 5.px,
          ),
          ExpandedWidget(
            key: cutDownWidgetKey,
            defaultHeight: 0,
            child: buildVideoPlayVideoInfoVideoDetails(),
          ),
          SizedBox(
            height: 10.px,
          ),
          buildVideoPlayVideoInfoButtonBanner(),
        ],
      ),
    );
  }

  Widget buildVideoPlayVideoInfoVideoDetails() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              widget.video.bvid,
              style: TextStyle(
                  color: HYAppTheme.norGrayColor,
                  fontSize: HYAppTheme.xxSmallFontSize),
            ),
            SizedBox(
              width: 8.px,
            ),
            buildIconInfo("assets/image/icon/ban_custom.png", "未经作者授权禁止转载"),
          ],
        ),
        SizedBox(
          height: 8.px,
        ),
        Text(
          widget.video.desc,
          style: TextStyle(
              color: HYAppTheme.norGrayColor,
              fontSize: HYAppTheme.xxSmallFontSize),
        ),
        SizedBox(height: 30.px),
        Wrap(
          spacing: 10.px,
          runSpacing: 15.px,
          alignment: WrapAlignment.start,
          children: tagWidgets,
        )
      ],
    );
  }

  Widget buildVideoTag(String text) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 6.px, horizontal: 12.px),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(50.px),
          color: Color.fromRGBO(246, 247, 249, 1)),
      child: Text(
        text,
        style: TextStyle(color: Color.fromRGBO(100, 101, 103, 1)),
      ),
    );
  }

  Widget buildVideoPlayVideoInfoOwnerInfo(String ownerIcon, String ownerName) {
    return Row(
      children: [
        buildVideoPlayUserIcon(ownerIcon),
        Expanded(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 10.px),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  ownerName,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: HYAppTheme.norTextColors),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "$_followers粉丝",
                      style: TextStyle(
                          color: HYAppTheme.norGrayColor,
                          fontSize: HYAppTheme.xxSmallFontSize),
                    ),
                    SizedBox(width: 10.px),
                    Text(
                      "$_videos视频",
                      style: TextStyle(
                          color: HYAppTheme.norGrayColor,
                          fontSize: HYAppTheme.xxSmallFontSize),
                    )
                  ],
                )
              ],
            ),
          ),
        ),
        TextButton(
          child: const Text(
            "+  关注",
          ),
          onPressed: () {},
          style: TextButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 13.px),
              backgroundColor: HYAppTheme.norTextColors,
              textStyle: TextStyle(fontSize: 13.px, color: Colors.white)),
        )
      ],
    );
  }

  //圆形图标
  Widget buildVideoPlayUserIcon(String userLogo) {
    return Container(
      alignment: Alignment.centerLeft,
      child: CircleAvatar(
        backgroundImage: NetworkImage(userLogo),
      ),
    );
  }

  Widget buildVideoPlayVideoInfoVideoTitle() {
    return Column(
      children: [
        GestureDetector(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: isExpanded == false
                    ? Text(
                        widget.video.title,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.black, fontSize: 17.px),
                      )
                    : Text(
                        widget.video.title,
                        style: TextStyle(color: Colors.black, fontSize: 17.px),
                      ),
              ),
              isExpanded == true
                  ? Image.asset(
                      ImageAssets.icArrowUpPNG,
                      width: 23.px,
                      height: 23.px,
                    )
                  : Image.asset(
                      ImageAssets.icArrowDownPNG,
                      width: 23.px,
                      height: 23.px,
                    ),
            ],
          ),
          onTap: () {
            isExpanded = !isExpanded;
            cutDownWidgetKey.currentState?.widgetShift();
            if (mounted) setState(() {});
          },
        ),
        SizedBox(
          height: 10.px,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            buildIconInfo("assets/image/icon/play_custom02.png",
                changeToWan(widget.video.stat["view"] ?? 0)),
            SizedBox(
              width: 10.px,
            ),
            buildIconInfo("assets/image/icon/remark_custom02.png",
                changeToWan(widget.video.stat["danmaku"] ?? 0)),
            SizedBox(
              width: 10.px,
            ),
            Text(
              getPubDataText(widget.video.pubdate),
              style: TextStyle(
                  color: HYAppTheme.norGrayColor,
                  fontSize: HYAppTheme.xxSmallFontSize),
            )
          ],
        ),
      ],
    );
  }

  Widget buildVideoPlayVideoInfoButtonBanner() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        buildVideoPlayIconButton("assets/image/icon/like_custom.png",
            changeToWan(widget.video.stat["like"] ?? 0)),
        buildVideoPlayIconButton("assets/image/icon/dislike_custom.png", "不喜欢"),
        buildVideoPlayIconButton("assets/image/icon/coin_custom.png",
            changeToWan(widget.video.stat["coin"] ?? 0)),
        buildVideoPlayIconButton("assets/image/icon/collect_custom.png",
            changeToWan(widget.video.stat["favorite"] ?? 0)),
        buildVideoPlayIconButton("assets/image/icon/share_custom.png",
            changeToWan(widget.video.stat["share"] ?? 0)),
      ],
    );
  }

  Widget buildVideoPlayIconButton(String icon, String text) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(
          icon,
          width: 27.px,
          height: 27.px,
          color: Color.fromRGBO(95, 103, 106, 1),
        ),
        SizedBox(height: 10.px),
        Text(
          text,
          style: TextStyle(
              color: HYAppTheme.norGrayColor,
              fontSize: HYAppTheme.xxSmallFontSize),
        )
      ],
    );
  }
}

//参考https://www.jianshu.com/p/a55184ee0d24
class ExpandedWidget extends StatefulWidget {
  Widget child;
  double defaultHeight;
  Key key;

  ExpandedWidget(
      {required this.child, required this.defaultHeight, required this.key});

  @override
  State<ExpandedWidget> createState() => _ExpandedWidgetState();
}

class _ExpandedWidgetState extends State<ExpandedWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> curve;
  late Animation<double> videoDetailsHeightAnimation;
  late ScrollController scrollController;
  late double realHeight = 0;
  late HeightReporter heightReporter;

  @override
  void initState() {
    controller =
        AnimationController(vsync: this, duration: Duration(milliseconds: 250));
    curve = CurvedAnimation(parent: controller, curve: Curves.easeOut);
    videoDetailsHeightAnimation =
        Tween(begin: 0.0, end: realHeight).animate(controller);
    scrollController = ScrollController();
    heightReporter = HeightReporter(
      child: widget.child,
    );
    super.initState();
  }

  widgetShift() {
    // print('heightReporter.getHeight()----${heightReporter.getHeight()}');
    realHeight = heightReporter.getHeight() ?? 0;
    videoDetailsHeightAnimation =
        Tween(begin: 0.0, end: realHeight).animate(controller)
          ..addListener(() {
            setState(() {});
          });
    videoDetailsHeightAnimation.value == widget.defaultHeight
        ? controller.forward()
        : controller.reverse();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: videoDetailsHeightAnimation.value,

      ///在SingleChildScrollView里面外层的组件设置了高度，SingleChildScrollView也可以获取到你想要的组件的高度
      ///不嵌套SingleChildScrollView，只会获得零高度
      child: SingleChildScrollView(
        child: heightReporter,
        physics: NeverScrollableScrollPhysics(),
        controller: scrollController,
      ),
    );
  }
}
